package com.jule.teenpatti.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.jule.core.common.log.LoggerUtils;
import com.jule.teenpatti.base.enums.GameConst;
import com.jule.teenpatti.game.network.protocol.ClientReq;
import com.jule.teenpatti.game.network.protocol.acks.JoloGame_GiftsListAck_50051;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.service.ProductionService;
import com.jule.teenpatti.game.service.TableService;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JoloGame_GiftsListReq_50051 extends ClientReq {
    private long time;

    public JoloGame_GiftsListReq_50051(int functionId) {
        super(functionId);
    }

    private JoloGame.JoloGame_GiftsListReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloGame.JoloGame_GiftsListReq.parseFrom(blob);
        AbstractTable table = TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId());
        if (null != table) {
            this.setTable(table);
        } else {
            log.error("桌子不存在,roomId->" + req.getRoomId() + ", tableId->" + req.getTableId());
        }
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + " reqNum-> " + header.reqNum + " " + req.toString());
        AbstractTable table = getTable();
        if (table == null) {
            log.debug("giftListReq, table is null");
            return;
        }
        try {
            JoloGame.JoloGame_GiftsListAck.Builder ack = JoloGame.JoloGame_GiftsListAck.newBuilder();
            ack.setRoomId(table.getRoomId()).setTableId(table.getTableId()).setUserId(req.getUserId())
                    .addAllItemInfoList(ProductionService.getInstance().getAllGiftConfig())
                    .addAllLimitItemList(ProductionService.getInstance().getLimitGiftConfig()).setResult(1);
            ctx.writeAndFlush(new JoloGame_GiftsListAck_50051(ack.build(), header));
            log.debug("giftListReq, send");
            long timeMillis = System.currentTimeMillis() - time;
            if (timeMillis > GameConst.COST_TIME) {
                LoggerUtils.performance.info("GiftsListReq_50051,cost time:{},req:{}", timeMillis, req.toString());
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            long useTimes = System.currentTimeMillis() - time;
            if(useTimes > 500) {
                log.error("GiftsList。 耗时->{} 毫秒, reqNum->{}", useTimes, header.reqNum); //TODO:临时增加
            }
        }
    }
}
